package com.demo.controller;

import com.demo.bean.Lesson;
import com.demo.bean.User;
import com.demo.mapper.LessonMapper;
import com.demo.service.AnalysisHtmlService;
import com.demo.service.ExecutePythonService;
import com.demo.service.LessonSaveService;
import com.demo.service.RedisService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @author 李天航
 * 获得爬取的课程信息
 */
@RestController
@RequestMapping("/lesson")
public class LessonGetController {

    @Resource
    RedisService redisService;
    @Resource
    LessonSaveService lessonSaveService;
    @Resource
    LessonMapper lessonMapper;

    /**
     * 使用爬虫爬取课表
     * @return status,msg
     */
    @PostMapping("/get")
    public Object getLessonsByLogin(HttpServletRequest request){
        LinkedHashMap<String, Object> resultMap = new LinkedHashMap<>();
        try {
            String sessionId=request.getHeader("sessionId");
            if(sessionId==null){
                resultMap.put("status",500);
                resultMap.put("msg","请先登录");
                return resultMap;
            }
            User user= (User) redisService.getSessionData(sessionId,"user");
            if(user==null){
                resultMap.put("status",500);
                resultMap.put("msg","请先登录");
                return resultMap;
            }
            if(user.getUserSno()==null||user.getUserSnoPwd()==null){
                resultMap.put("status",501);
                resultMap.put("msg","请输入学号和密码");
                return resultMap;
            }
            String rawSessionId= redisService.getSessionIdByUserAccount(user.getUserAccount());
            if(rawSessionId==null|| !rawSessionId.equals(sessionId)){
                resultMap.put("status",500);
                resultMap.put("msg","该账号已登录，请重新登录");
                return resultMap;
            }
            System.out.println(user.getUserSno());
            System.out.println(user.getUserSnoPwd());
            return lessonSaveService.getLessonsAndSave(
                    user.getUserSno(), user.getUserSnoPwd(),user.getUserAccount());
        }catch (Exception e){
            resultMap.put("status",500);
            resultMap.put("msg",e.getMessage());
            e.printStackTrace();
        }
        return resultMap;
    }
    @PostMapping("/clear")
    public Object clearLessons(String userAccount,HttpServletRequest request){
        lessonMapper.clearLessons(userAccount);
        return "ok";
    }
}
